package com.dkm.orproject.dkmoa.action;

import com.alibaba.fastjson.JSON;
import com.dkm.orproject.dkmoa.domain.OaLog;
import com.dkm.orproject.dkmoa.domain.OaPersonnel;
import com.dkm.orproject.dkmoa.domain.OaSchdule;
import com.dkm.orproject.dkmoa.service.OaSchduleService;
import com.dkm.orproject.utils.jwt.login.UserLoginToken;
import com.dkm.orproject.utils.utils.Tools;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *  @ClassName : OaSchduleAction  //类名
 *  @Description : 日程管理  //描述
 *  @Author : 石智诚  //作者
 *  @Date: 2020-11-18 11:51  //时间
 */
@RestController
@RequestMapping("/OaSchduleAction")
public class OaSchduleAction {
    /**
     * 日程管理
     */
    @Resource
    OaSchduleService oaSchduleService;

    /**
     * 工具类
     */
    @Resource
    Tools tools;


    /**
     * 回调值
     */
    int row=0;

    /**
     * 日志
     */
    OaLog log;

    /**
     * 登陆人
     */
    OaPersonnel personnel;

    /**
     * 回调map
     */
    Map<String,Object> map;

    @UserLoginToken
    @GetMapping("schduleFindAll")
    public Map<String,Object> schduleFindAll(OaSchdule schdule,Integer limit,Integer page,
                                            String startDate,String endDate,HttpServletRequest request){
        rowMap(request);
        if (ObjectUtils.isEmpty(personnel)){
            tools.rowMap(map,0,log);
        }
        try {
            List<OaSchdule> all = oaSchduleService.findAll(schdule, limit, page, startDate, endDate);
            Long count = oaSchduleService.rowCount(schdule, startDate, endDate);
          return   Tools.maps(all,count);
        } catch (Exception e) {
            addErrorLog(request,"日程查看",e);
        }
        return null;
    }
    /**
     *
     * @param id 日程Id
     * @param request 请求
     * @return map
     */
    @UserLoginToken
    @GetMapping("schduleFindById/{id}")
    public OaSchdule shduleFindById(@PathVariable("id") Long id, HttpServletRequest request){
        rowMap(request);
        if (ObjectUtils.isEmpty(personnel)) {
            tools.rowMap(map,0,log);
        }
        try {
            return oaSchduleService.selectByPrimaryKey(id);

        } catch (Exception e) {
            addErrorLog(request,"日程根据id查找",e);
        }
        return  null;
    }
    @UserLoginToken
    @DeleteMapping("schduleDeleteById/{id}")
    public Map<String,Object> deleteById(@PathVariable("id") Long id,HttpServletRequest request){
        rowMap(request);
        if (ObjectUtils.isEmpty(personnel)) {
            tools.rowMap(map,0,log);
        }
        try {
            OaSchdule oaSchdule = oaSchduleService.selectByPrimaryKey(id);
            row=oaSchduleService.deleteByPrimaryKey(id);
            log.setLogTitle("删除模块");
            log.setLogBody(JSON.toJSON(oaSchdule).toString());
            log.setLogType("1");
            tools.rowMap(map, row, log);
        } catch (Exception e) {
           addErrorLog(request,"日程根据id删除",e);
        }
        return  map;
    }
    @UserLoginToken
    @DeleteMapping("schduleDeleteAll")
    public Map<String,Object> deleteById(@RequestParam("id[]") Long[] ids,HttpServletRequest request){
        rowMap(request);
        if (ObjectUtils.isEmpty(personnel)) {
            tools.rowMap(map,0,log);
        }
        try {
            List<Long> list = Arrays.asList(ids);
            List<OaSchdule> schdules = oaSchduleService.selectAll(list);
            row=oaSchduleService.deleteAll(list);
            log.setLogTitle("删除模块");
            log.setLogBody(JSON.toJSON(schdules).toString());
            log.setLogType("1");
            tools.rowMap(map, row, log);
        } catch (Exception e) {
            addErrorLog(request,"日程根据id删除",e);
        }
        return  map;
    }

    @UserLoginToken
    @PostMapping("schduleAddOrUpdate")
    public Map<String, Object> addOrUpdate(OaSchdule schdule,HttpServletRequest request){
        rowMap(request);
        if (ObjectUtils.isEmpty(personnel)){
            tools.rowMap(map,0,log);
        }
        try {
            if (schdule.getPkSchduleId()!=null&& schdule.getPkSchduleId()>0){
                schdule.setUpdatedBy(personnel.getPersonnelName());
                schdule.setUpdatedTime(new Date());
                row = oaSchduleService.updateByPrimaryKeySelective(schdule);
               log.setLogTitle("日程更新");
            }else {
                schdule.setCreatedBy(personnel.getPersonnelName());
                schdule.setCreatedTime(new Date());
                row=oaSchduleService.insertSelective(schdule);
                log.setLogTitle("日程增加");
            }
            log.setLogBody(JSON.toJSON(schdule).toString());
            log.setIsRevision("1");
            tools.rowMap(map,row,log);
        } catch (Exception e) {
            addErrorLog(request,"日程更新或者更新",e);
        }
        return  map;
    }

    /**
     * 收集报错日志
     * @param request 请求 用于得到当前登录人和ip地址
     * @param title 模块标题
     * @param e 异常参数
     */
    private void addErrorLog(HttpServletRequest request,String title,Exception e){
        //后台打印报错信息
        e.printStackTrace();
        //获取当前操作人
        personnel= (OaPersonnel) request.getSession().getAttribute("user");
        //新建日志
        log=new OaLog();
        //日志类型
        log.setLogType("0");
        //日志内容
        log.setLogBody(e.getLocalizedMessage());
        //日志标题
        log.setLogTitle(title);
        //请求地址
        log.setLogIp(request.getRemoteAddr());
        //判断当前登陆人是否存在
        if(ObjectUtils.isEmpty(personnel)){
            //当前操作人名称
            log.setCreatedBy(personnel.getPersonnelName());
        }
        //存入报错日志
        tools.errorMap(log);
    }
    /**
     * 优化代码 获取当前登陆人信息
     * @param request 服务器请求
     */
    private void rowMap(HttpServletRequest request){
        //新建返回Map模型
        map=new HashMap<>(16);
        //获取登陆人信息
        personnel= (OaPersonnel) request.getSession().getAttribute("user");
        //为空则清空map
        if(ObjectUtils.isEmpty(personnel)){
            return;
        }
        //新建日志
        log=new OaLog();
        //得到ip
        log.setLogIp(request.getRemoteAddr());
        //登陆人名称
        log.setCreatedBy(personnel.getPersonnelName());
    }

    /**
     * 日期格式化
     *
     * @param binder 服务器参数转换器
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // true:允许输入空值，false:不能为空值
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

}
